var express = require('express');
var router = express.Router();
var DateModule = require('../../databases/date')
const { gouwu } = require('../../databases/date');
const { shops } = require('../../databases/date');
const mongoose = require('mongoose');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/cart', async (req, res) => {
  try {
    const { userId, search } = req.query;
    let query = {};
    if (userId) {
      try {
        query.userId = mongoose.Types.ObjectId(userId);
      } catch {
        query.userId = userId;
      }
    }
    const cartList = await gouwu.find(query).lean();
    // 批量查商品详情
    const shopIds = cartList.map(item => item.shopId);
    const shopList = await shops.find({ _id: { $in: shopIds } }).lean();
    // 用id做映射
    const shopMap = {};
    for (let shop of shopList) {
      shopMap[shop._id.toString()] = shop;
    }
    // 合并商品信息
    let result = [];
    for (let item of cartList) {
      const shop = shopMap[item.shopId.toString()];
      if (shop) {
        item.price = shop.price;
        item.name = shop.name;
        item.images = shop.images;
        // 搜索过滤
        if (search && !shop.name.includes(search)) continue;
      }
      result.push(item);
    }
    res.json({ code: 0, data: result, msg: '获取成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 1, msg: '服务器错误', error: err.message });
  }
});

// 删除购物车商品接口
router.delete('/cart/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const result = await gouwu.deleteOne({ _id: id });
    if (result.deletedCount > 0) {
      res.json({ code: 0, msg: '删除成功' });
    } else {
      res.json({ code: 1, msg: '未找到该购物车项' });
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 1, msg: '服务器错误', error: err.message });
  }
});

// 批量删除购物车商品接口
router.delete('/cart', async (req, res) => {
  try {
    const { ids } = req.body;
    if (!Array.isArray(ids) || ids.length < 1) {
      return res.json({ code: 1, msg: '请选择要删除的商品' });
    }
    const result = await gouwu.deleteMany({ _id: { $in: ids } });
    res.json({ code: 0, msg: `成功删除${result.deletedCount}项` });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 1, msg: '服务器错误', error: err.message });
  }
});

// 生成订单接口
router.post('/order', async (req, res) => {
  try {
    const { userId, items } = req.body;
    if (!userId || !Array.isArray(items) || items.length < 1) {
      return res.json({ code: 1, msg: '参数错误' });
    }
    const { dingdan } = require('../../databases/date');
    // 生成唯一订单号
    const orderNo = 'DD' + Date.now() + Math.floor(Math.random() * 10000);
    // 构造订单数据
    const orderDocs = items.map(item => ({
      userId,
      shopsId: item.shopId,
      colorx: item.colorx,
      chima: item.chima,
      num: item.num,
      cart: 'A',
      orderNo
    }));
    await dingdan.insertMany(orderDocs);
    res.json({ code: 0, msg: '订单生成成功', orderNo });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 1, msg: '服务器错误', error: err.message });
  }
});

module.exports = router;